package com.syxbyi.hmwk1.main;

import java.util.Arrays;
import java.util.Objects;
import java.util.Random;

/*
自定义数组扩容规则，当已存储元素数量达到总容量的 80%时，扩容 1.5 倍。
例如，总容量是 10，当输入第 8 个元素时，数组进行扩容，容量从 10 变 15
 */
public class ArrayExpansion<T> {
    private Object[] elements;
    private int initialCapacity = 10;
    private int size;

    public ArrayExpansion() {
        elements = new Object[initialCapacity];
    }

    public ArrayExpansion(int initialCapacity) {
        if (initialCapacity > 0) {
            this.initialCapacity = initialCapacity;
        }
        elements = new Object[this.initialCapacity];
    }

    public void add(T t) {
        size += 1;
        if (size * 5 >= elements.length * 4) {
            int newLen = (int)(elements.length * 1.5);
            System.out.printf("数组扩容 %d -> %d\n", elements.length, newLen);
            elements = Arrays.copyOf(elements, newLen);
        }
        elements[size - 1] = t;
    }

    public void remove(int index) {
        Objects.checkIndex(index, size);
        size -= 1;
        System.arraycopy(elements, index + 1, elements, index, size - index);
        elements[size] = null;
    }

    @Override
    public String toString() {
        return Arrays.toString(elements);
    }

    public static void main(String[] args) {
        ArrayExpansion<String> t = new ArrayExpansion<>();
        Random random = new Random();
        for (int i = 1; i <= 20; i++) {
            String s = String.valueOf(random.nextInt());
            t.add(s);
            System.out.printf("%d: add element %s\n", i, s);
        }
        System.out.println(t);
    }
}
